#pragma once 

#include<iostream>
#include<signal.h>
#include<functional>
#include"Sock.hpp"

class HttpServer
{
public:
    //定义函数指针类型，该函数不需要返回
    using func_t = std::function<void(int)>;

private:
    int listensock_;
    uint16_t port_;
    Sock sock;
    func_t func_;
  

public:
  HttpServer(const uint16_t &port,func_t func):port_(port),func_(func)
  {
    listensock_ = sock.Socket();
    sock.Bind(listensock_,port_);
    sock.Listen(listensock_);
  }

  ~HttpServer()
  {
      if(listensock_>=0) close(listensock_);    
  }

  
  void Start()
  {
    //SIGCHLD：父进程等待子进程退出信号；SIG_IGN忽略信号；目的：让操作系统去回收子进程，防止僵尸进程的出现
    signal(SIGCHLD, SIG_IGN);
    for( ; ;)
    {
        std::string clientIp;
        uint16_t clientPort =0;
        int sockfd = sock.Accept(listensock_,&clientIp,&clientPort);
        if(sockfd<0) continue;
        if(fork()==0)
        {
            close(listensock_);
            func_(sockfd);
            close(sockfd);
            exit(0);
        }
        close(sockfd);      
    }
  }

};